package cn.yuanqiao.activiti.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class PdfUtil {

    /**
     * pdf插入图片
     *
     * @param
     * @param newPath 插入图片后的路径
     * @param
     * @throws IOException
     * @throws DocumentException
     */
    public static void addImage(InputStream inputStream, String newPath, byte[] waterMarkImage,int x,int y,float width,float height,boolean isALLAdd) throws IOException, DocumentException {
        //InputStream inputStream = oldPath;
        FileOutputStream out = new FileOutputStream(new File(newPath));
        PdfReader reader = new PdfReader(inputStream);
        //pdf页数
        int pdfPages = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, out);
        //图片
        //BufferedImage bufferedImage = ImageIO.read(Files.newInputStream(Paths.get(imgPath)));

        //x轴坐标
        //int x = 350;
        //y轴坐标
        //int y = 390;
        //图片放置的页码
        PdfContentByte content;
        if(isALLAdd) pdfPages = 1;
        for (int i = 1; i <= pdfPages; i++) {
            //图片处理
            content = stamper.getOverContent(i);
            content.beginText();
            //Image img = Image.getInstance(ImageUtil.imageToBytes((bufferedImage), "png"));
            Image img = Image.getInstance(waterMarkImage);
            //设置图片大小
            content.saveState();
            img.scaleAbsolute(width, height);
            //img.setTransparency(new int[0]);
            //设置图片位置
            img.setAbsolutePosition(x, y);
            //PdfContentByte content = stamper.getOverContent(i);
            PdfGState gs = new PdfGState();
            //设置图片的透明度
            gs.setFillOpacity(1f);
            //gs.setFillOpacity(0.2f);

            content.setGState(gs);
            content.addImage(img);
            content.restoreState();
            content.endText();
        }
        //bufferedImage.flush();
        //inputStream.close();
        //关闭资源
        stamper.close();
        reader.close();
        out.close();
    }

    public static void main(String[] args) {
        //try {
            System.out.println("=====添加归档章开始=====");
            //PdfUtil.addImage("E:\\exportlog\\test-pdf.pdf", "E:\\exportlog\\test-pdf-water.pdf", "E:\\exportlog\\1.png");
            System.out.println("=====添加归档章结束=====");
        //} catch (IOException | DocumentException e) {
            //throw new RuntimeException(e);
        ////}
    }

}
